﻿App.Notice = function() {
    return {

        currentFormValues: {},

        getStore: function() {
            var store = new Ext.data.Store({
            	autoLoad:true,
				baseParams:{start:0, limit:15},
				proxy: new Ext.data.HttpProxy({
					url : 'notice/noticelist'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'id',
					fields: [{
						name: 'id',
						type: 'string'
					},
					{
						name: 'title',
						type: 'string'
					},
					{
						name: 'name',
						type: 'string'
					},
					{
						name: 'create_date',
						type: 'date',
						dateFormat: 'time'
					},{
						name: 'modify_date',
						type: 'date',
						dateFormat: 'time'
					}]
				})
            });
            return store;
        },

        getForm: function() {
            var form = new Ext.form.FormPanel({
				url:'notice/save',
                labelAlign: 'top',
                buttonAlign: 'center',
                bodyStyle: 'padding:5px',
                frame: true,
                labelWidth: 80,
                defaultType: 'textfield',
                defaults: {
                    allowBlank: true,
                    anchor: '100%',
                    enableKeyEvents: true
                },
                items: [{
                    xtype: 'hidden',
                    name: 'id',
                    value: ''
                },
                {
                    name: 'title',
                    fieldLabel: '标题',
                    allowBlank:true
                },{
                    name: 'message',
                    fieldLabel: '公告内容',
                    xtype:'htmleditor',
                    enableSourceEdit:false
                }],
                buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
            });
            return form;
        },

        submit: function() {
            if (this.form.getForm().isValid()) {
                this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                        var info = action.result.info;
                        if (action.result.success) {
                            this.store.reload();
                            this.form.getForm().reset();
                            this.dlg.hide();
                            var panel = Ext.getCmp('Notice');
                    		panel.remove('panelHtml');
                    		panel.doLayout();
                        }
                        Ext.Msg.alert('信息', info);
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });
            }
        },

        getDialog: function() {
            var dlg = new Ext.Window({
                width: 550,
                height: 460,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.form],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.form.getForm().waitMsgTarget = fp.getEl();
                    },
                    show: function() {
                        var f = this.form.getForm();
                        
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }
            });
            return dlg;
        },
        highLight: function(value) {
        	var key = App.Notice.grid.store.baseParams.query;
        	var v = value ? value.toString() : '';
        	if (Ext.isString(v) & Ext.isString(key)) {
        		if (key.length > 0) {
        			var re = new RegExp(key, "g");
        			return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
        		} else {
        			return v;
        		}
        	} else {
        		return v;
        	}
        },
        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.RowSelectionModel({singleSelect:true});

            this.grid = new Ext.grid.GridPanel({
            	tbar: new Ext.PagingToolbar({
            		pageSize: 15 ,//分页必须加的参数.最好和store里面的limit保持一致
                    displayInfo: true,
                    store: this.store,
                    items: ['-', 
                          {
                        text: '增加',
                        scope: this,
                        handler: this.add
                    },
                    {
                        text: '编辑',
                        scope: this,
                        handler: this.edit
                    },
                    {
                        text: '删除',
                        scope: this,
                        handler: this.del
                    },
                    '-', new Ext.ux.form.SearchField({
                        store: this.store,
                        width: 110
                    })]
                }),
                title:"公告管理",//打印必须设置tile
//                plugins: [Ext.ux.plugins.Print],//打印按钮
                loadMask: true,
                viewConfig : {autoFill:false,forceFit:true},
                autoHeight:true,
                store: this.store,
                sm: sm,
                columns: [{
                    header: "标题",
                    width: 150,
                    sortable: true,
                    dataIndex: 'title',
                    renderer:this.highLight
                },
                {
                    header: "发布公告人",
                    width: 100,
                    sortable: true,
                    dataIndex: 'name',
                    renderer:this.highLight
                },
                {
                    header: "发布日期",
                    width: 100,
                    sortable: true,
                    dataIndex: 'create_date',
                    renderer: Ext.util.Format.dateRenderer('Y-m-d h:m:s')
                },{
                	header:'修改日期',
                	 width: 100,
                     sortable: true,
                     dataIndex: 'modify_date',
                     renderer: Ext.util.Format.dateRenderer('Y-m-d h:m:s')
                }],
                listeners:{
            		scope: this,
            		rowclick : function(grid,index){
            			var win = new Ext.Window({title:'正在查询公告内容',modal:true,width: 250,height: 100});
            			win.show();//显示loading窗口
            			win.body.mask("数据读取中...", 'x-mask-loading');
            			var id = grid.getSelectionModel().getSelected().get('id');
            			Ext.Ajax.request({
                            waitMsg: '数据读取中',
                            url: 'notice/getmessagebyid', //请求URL(JSP/Servlet)
                            params: {id: id }, //设置传递参数
                            success: function(resp, opts) {//成功后的回调方法
                            	var respText = Ext.util.JSON.decode(resp.responseText); //解码JSON格式数据为一个对象
                            	win.body.unmask();
                            	win.hide();
                            	if(respText.success){
                            		 Ext.apply(App.Notice.currentFormValues, {
                                         message: respText.rows
                                     });
                            		var panel = Ext.getCmp('Notice');
                            		panel.remove('panelHtml');
                            		panel.add(new Ext.Panel({id:'panelHtml',html:respText.rows}));
                            		panel.doLayout();
                            	}else{
                            		Ext.apply(App.Notice.currentFormValues, {
                                        message: ""
                                    });
                            		Ext.Msg.alert('提示',"该公告数据库没有记录,请删除" );
                            	}
                            },
                            failure: function(resp, opts) {//失败 
                            	win.body.unmask();
                            	win.hide();
                                var respText = Ext.util.JSON.decode(resp.responseText);
                                Ext.Msg.alert('网络错误', respText.error);
                            }
                        }); 
            		}
            	}
            });
            panel.add(this.grid);

        },
        
        add: function() {
            Ext.apply(this.currentFormValues, {
                id: '',
                title:'',
                message: ""
            });
            this.dlg.setTitle("发布公告");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑公告");
                var rec = this.grid.getSelectionModel().getSelected();
                Ext.apply(this.currentFormValues, {
                	id: rec.data.id,
                    title: rec.data.title
                });
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的用户。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelected();
                var id = recs.get('id');
                Ext.Msg.confirm('删除用户', '确定删除吗？<br><font color="red">' + recs.get("title") + '</font>',
                function(btn) {
                    if (btn == 'yes') {
						Ext.Ajax.request({
							method:'post',
							url:'notice/deletenotice',
							params:{
								id:id
							},
							success: function(resp, opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								if(result.success==true) {
									Ext.Msg.alert('信息', info);
									App.Notice.store.reload();
									var panel = Ext.getCmp('Notice');
                            		panel.remove('panelHtml');
                            		panel.doLayout();
								}else {
                                    Ext.Msg.alert('信息', info);
                                }
							},
							failure: function(resp,opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								Ext.Msg.alert('提示', info); 
							}
						});
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的公告！');
            }
        },

        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            };
            if (!this.form) {
                this.form = this.getForm();
            };
            if (!this.dlg) {
                this.dlg = this.getDialog();
            };
            this.createGrid(id);

        }
    };
} ();
